<?php
/*
 * 文件名称: mysql.php

 * 功能: MYSQL 操作类

 * 创建: 2005-8-11

 * update: 2007-11-13 2010/6/14-Ricky
 */

class Mysql
{
	var $DBConn; //数据库连接
	var $DBName; //数据库名

	function __construct()
	{
		//类初始化，建立数据连接
		global $CFG;
		$this->connect($CFG['db']['host'].':'.$CFG['db']['port'],$CFG['db']['user'],$CFG['db']['pwd']);
		$this->selectDb($CFG['db']['name']);
		$this->query('SET NAMES \'UTF8\'');
	}

	//连接服务器
	function connect($host,$user,$pwd)
	{
		$conn = @mysql_connect($host,$user,$pwd); //连接mysql
		if (!$conn){
			global $CFG;
			$msg = "连接数据库失败!\n".mysql_error();
			$this->errLog($CFG["db"]["err_log_file"], $msg); //写错误日志
			$this->errMsg($msg);
		}else{
			$this->DBConn = $conn; //暂存数据库连接
		}
	}

	//选定数据库
	function selectDb($db_name)
	{
		$this->DBName = $db_name;
		if (!mysql_select_db($db_name, $this->DBConn)){
			$this->errMsg("选定数据库[{$db_name}]失败!");
		}
	}

	//执行查询
	function query($sql, $Type = MYSQL_BOTH) //MYSQL_BOTH, MYSQL_ASSOC, MYSQL_NUM
	{
		if (empty($sql)){
			$this->errMsg("未指定查询语句!");
		}

		$result = @mysql_query($sql);
		if (!$result){
			global $CFG;
			if ($CFG["db"]["err_log"]){
				$msg = "src: ".request_uri()."\nsql: {$sql}\n".mysql_error()."\nDate:".date("Y-m-d H:i:s")."\n\n";
				$this->errLog($CFG["db"]["err_log_file"], $msg); //写错误日志
			}
			$this->errMsg("执行查询出错:\n<br/>SQL: {$sql}\n<br/>".mysql_error());
		}else{
			if (preg_match("/^\(?select/isU",$sql)){
				$re_arr = array();
				while($re_rs = mysql_fetch_array($result,$Type)){
					$re_arr[] = $re_rs;
				}
				mysql_free_result($result);
				return $re_arr;
			}
			return true;
		}
	}

	//取最后一次insert的记录id
	function insertId()
	{
        return mysql_insert_id();
    }

	//取最后一次执行语句影响的记录数
	function processNum($dbconn = null)
	{
		if ($dbconn==null){
			$dbconn = $this->DBConn;
		}
		return mysql_affected_rows($dbconn);
	}

	//释放数据库连接
	function close()
	{
		mysql_close($this->DBConn);
	}

	//显示错误信息
	function errMsg($msg)
	{
		global $CFG;
		if (isset($CFG["err"])){
			switch ($CFG["err"]["mode"]){
				case 1:
					header("Location: {$CFG['err']['page']}");
					die();
					break;

				case 2:
					return;
					break;
			}
		}
		die("<style>body{font-size:12px;}</style><br/><font color=red>Mysql class 错误:</font><hr size=1 color=#0099ff>来源: {$_SERVER['REQUEST_URI']}<br/>信息: {$msg}");
	}

	//写数据库错误日志
	function errLog($file_name, $msg)
	{
		$fh = @fopen($file_name, "a+");
		if($fh){
			fwrite($fh, date("Y-m-d H:i:s") . ' - ' . $msg);
			fclose($fh);
		}else{
			echo "can not write sql err_log.\n<br/>";
		}
	}
}
?>